package ru.surfstudio.graduate.activity;

import java.util.ArrayList;
import java.util.List;


import ru.surfstudio.graduate.R;
import ru.surfstudio.graduate.data.Channel;
import ru.surfstudio.graduate.handler.FeedsAddHandler;
import ru.surfstudio.graduate.service.HttpService;
import ru.surfstudio.graduate.task.FeedSearchTask;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Messenger;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ChannelResultActivity extends AbstractRssActivity {
	
	public static final String MARK_CHANNEL_LIST = "CHANNEL_LIST";
	public static final String MARK_SEARCH_TEXT = "SEARCH_TEXT";
	
	private static final String TAG = "ChannelResultActivity";
	
	private static final int DIALOG_ADD = 0x2;
	
	private static final String POSITION = "POSITION";
	
	private ChannelResultAdapter adapter;
	private List<Channel> channelList;
	
	private ListView channelListView;
	
	private ChannelResultActivityState state;
	
	private int position;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_activity);
		
		channelList = (List<Channel>) getIntent().getSerializableExtra(MARK_CHANNEL_LIST);
		adapter = new ChannelResultAdapter(channelList != null ? channelList : 
			new ArrayList<Channel>());
		
		state = (ChannelResultActivityState) getLastNonConfigurationInstance();
		if (state == null) {
			state = new ChannelResultActivityState(this);
		} else {
			state.attach(this);
		}
		
		String titleStr =  String.format(getString(R.string.channel_result_title_label), 
				getIntent().getStringExtra(MARK_SEARCH_TEXT));
		setTitle(titleStr);
		
		channelListView = (ListView) findViewById(R.id.main_channels_list);
		channelListView.setAdapter(adapter);
		channelListView.setOnItemClickListener(onListClick);
		
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		
		state.detach();
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt(POSITION, position);
	}
	
	@Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		position = savedInstanceState.getInt(POSITION);
	}
	
	@Override
    public Object onRetainNonConfigurationInstance() {
        state.detach();
        return state;
    }
	
	@Override
	protected Dialog onCreateDialog(int id) {
		
		switch (id) {
			case DIALOG_ADD:
				return createAddingDialog();
		}
		return super.onCreateDialog(id);
	}
	
	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
			case DIALOG_ADD:
				((AlertDialog) dialog).setMessage(getDialogMess(position));
				break;
		}
	}
	
	@Override
	public void onPostFeedsUpdate(Channel channel) {
		Intent intent = new Intent(this, FeedListActivity.class);
		intent.putExtra(FeedListActivity.MARK_CHANNEL, channel);
		startActivity(intent);
	}
	
	public void setPosition(int position) {
		this.position = position;
	}
	
	private Dialog createAddingDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder
			.setTitle(R.string.channel_result_subscribe_dialog_title)
			.setMessage(getDialogMess(position))
			.setPositiveButton(R.string.ok, 
					new DialogInterface.OnClickListener() {
			
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Channel channel = adapter.getItem(position);
					if (channel == null) {
						Toast.makeText(ChannelResultActivity.this, 
								R.string.channel_result_load_error, 
						       Toast.LENGTH_SHORT);
						Log.w(TAG, getString(R.string.channel_result_load_error));
					} else {
						Intent intent = new Intent(ChannelResultActivity.this, HttpService.class);
						intent.putExtra(HttpService.MARK_HANDLER, new Messenger(state.handler));
						intent.putExtra(HttpService.MARK_TASK, new FeedSearchTask(channel));
						startService(intent);
					}

				}
			}).setNegativeButton(R.string.cancel, null);
		
		return builder.create();
	}
	
	/** Генерируем текст диалога для добавления channel */
	// Проверяем, что adapter не пуст, т.к. вызов метода onCreateDialog(int) 
	// может произойти раньше заполнения adapter
	private String getDialogMess(int position) {
		String name = "";
		if (!adapter.isEmpty())
			name = adapter.getItem(position).getName();
		return String.format(getString(R.string.channel_result_subscribe_dialog_label), 
							 name);
	}
	
	
	private AdapterView.OnItemClickListener onListClick = new AdapterView.OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			 setPosition(position);
			 showDialog(DIALOG_ADD);
		}
		
	};
	
	
	private class ChannelResultAdapter extends ArrayAdapter<Channel> {
		
		public ChannelResultAdapter(List<Channel> channelList) {
			super(ChannelResultActivity.this, R.layout.result_channel_list_item, channelList);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;
			if (row == null) {
				row = getLayoutInflater().inflate(R.layout.result_channel_list_item, null);
			}
			
			ViewHolder holder = (ViewHolder) row.getTag();
			if (holder == null) {
				holder = new ViewHolder(row);
				row.setTag(holder);
			}
			
			holder.nameView.setText(getItem(position).getName());
			
			return row;
		}
		
		private class ViewHolder {
			
			TextView nameView = null;
			  
			ViewHolder(View row) {
				nameView = (TextView) row.findViewById(R.id.result_channel_list_item_name_text);
			}
		}
		
	}
	
	/** Activity state */
    private static class ChannelResultActivityState {

        public FeedsAddHandler handler;

        public ChannelResultActivityState(ChannelResultActivity activity) {
            handler = new FeedsAddHandler(activity);
        }
        
        public void attach(ChannelResultActivity activity) {
        	handler.attach(activity);
        }
        
        public void detach() {
        	handler.detach();
        }
        
    }

}
